/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.transas.zornav.file;

import com.transas.zornav.data.DataSource;
import java.io.BufferedWriter;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author amalikov
 */
public class KmlDataSourceWriter implements DataSourceWriter {
	private final static Logger LOG = Logger.getLogger(KmlDataSourceWriter.class.getName());

	@Override
	public void process(BufferedWriter file, DataSource ds) {
		try {
			StreamResult streamResult = new StreamResult(file);
			TransformerFactory tf = TransformerFactory.newInstance();
			tf.setAttribute("indent-number", 4); 
			Transformer serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.METHOD, "xml");
			serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.transform(createDOMSource(ds), streamResult);
        } catch (TransformerException ex) {
			LOG.log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
	}

	private DOMSource createDOMSource(DataSource ds) throws ParserConfigurationException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		DocumentBuilder db = dbf.newDocumentBuilder();
		DOMImplementation impl = db.getDOMImplementation();
		Document doc = impl.createDocument("http://www.opengis.net/kml/2.2", "kml", null);
		
		doc.getDocumentElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:atom", "http://www.w3.org/2005/Atom");
		
		Element document = doc.createElement("Document");
		Element placemark = doc.createElement("Placemark");
		Element linestring = doc.createElement("LineString");
		Element coordinates = doc.createElement("coordinates");
		coordinates.setTextContent(createPoints(ds));
		linestring.appendChild(coordinates);
		placemark.appendChild(linestring);
		document.appendChild(placemark);
		doc.getDocumentElement().appendChild(document);
		
		return new DOMSource(doc);
	}

	private String createPoints(DataSource ds) {
		StringBuilder str = new StringBuilder("\n");
		
		NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
		nf.setMinimumFractionDigits(0);
		nf.setMaximumFractionDigits(12);
		nf.setGroupingUsed(false);
		
		for (int i = 0; i < ds.getSize(); ++i) {
			str.append(nf.format(ds.getValue(ds.getHandle("Longitude"), i))).append(",");
			str.append(nf.format(ds.getValue(ds.getHandle("Latitude"), i))).append(",");
			str.append(nf.format(ds.getValue(ds.getHandle("Altitude"), i))).append(" ");
		}
		
		str.append("\n");
		
		return str.toString();
	}
}
